package com.bianguo.android.baidumapdemo.widget;

import android.content.ContentValues;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import com.bianguo.android.baidumapdemo.R;
import com.bianguo.android.baidumapdemo.utils.MLog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

/**
 * Created by Administrator on 2018/3/1.
 */

public class SingerView extends View {
    private Paint mPaint, framePaint;
    private Path mPath;
    private float mPreX, mPreY;
    private String mFilePath;

    private ArrayList<Point> baiduPoints;
    private int n;
    private PaletteListener paletteListener;
    private boolean isClose;
    private float firstX;
    private float firstY;

    public void setPaletteListener(PaletteListener paletteListener) {
        this.paletteListener = paletteListener;
    }

    public SingerView(Context context) {
        super(context);
        init(context);
    }

    public SingerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public SingerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        //边框
        framePaint = new Paint();
        framePaint.setStyle(Paint.Style.STROKE);
        framePaint.setStrokeWidth(20);
        framePaint.setAntiAlias(true);
        framePaint.setColor(ActivityCompat.getColor(context, R.color.colorAccent));

        //画板
        mPaint = new Paint();
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setColor(Color.BLUE);
        mPaint.setStrokeWidth(10);
        mPaint.setAntiAlias(true);

        mPath = new Path();
        baiduPoints = new ArrayList<>();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //绘制边框
        canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), framePaint);
        //绘制画板
        canvas.drawColor(Color.TRANSPARENT);
//        canvas.drawRect(10, 10, getMeasuredWidth() - 10, getMeasuredHeight() - 10, mPaint);
        canvas.drawPath(mPath, mPaint);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                baiduPoints.clear();
                mPath.moveTo(event.getX(), event.getY());
                mPreX = event.getX();
                mPreY = event.getY();
                firstX = event.getRawX();
                firstY = event.getRawY();
                return true;
            case MotionEvent.ACTION_MOVE:
                Point baiduPoint = new Point();
                baiduPoint.x = (int) event.getX();
                baiduPoint.y = (int) event.getY();
                baiduPoints.add(baiduPoint);
                float endX = (mPreX + event.getX()) / 2;
                float endY = (mPreY + event.getY()) / 2;
                mPath.quadTo(mPreX, mPreY, endX, endY);
                mPreX = event.getX();
                mPreY = event.getY();
                if (firstX == event.getRawX() && firstY == event.getRawY()) {
                    isClose = true;
                }
                invalidate();
                break;
            case MotionEvent.ACTION_UP:
                if (paletteListener != null && baiduPoints.size() > 2) {
                    paletteListener.onFinishDraw(baiduPoints, isClose);
                }
                break;
        }
        return super.onTouchEvent(event);
    }

    public void reset() {
        mPath.reset();
    }

    public boolean saveToGallery(String fileName, String subFolderPath, String fileDescription, Bitmap.CompressFormat
            format, int quality) {
        // 控制图片质量
        if (quality < 0 || quality > 100)
            quality = 50;

        long currentTime = System.currentTimeMillis();

        File extBaseDir = Environment.getExternalStorageDirectory();
        File file = new File(extBaseDir.getAbsolutePath() + "/DCIM/" + subFolderPath);
        if (!file.exists()) {
            if (!file.mkdirs()) {
                return false;
            }
        }

        String mimeType = "";
        switch (format) {
            case PNG:
                mimeType = "image/png";
                if (!fileName.endsWith(".png"))
                    fileName += ".png";
                break;
            case WEBP:
                mimeType = "image/webp";
                if (!fileName.endsWith(".webp"))
                    fileName += ".webp";
                break;
            case JPEG:
            default:
                mimeType = "image/jpeg";
                if (!(fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")))
                    fileName += ".jpg";
                break;
        }

        mFilePath = file.getAbsolutePath() + "/" + fileName;
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(mFilePath);

            Bitmap b = getChartBitmap();
            b.compress(format, quality, out);

            out.flush();
            out.close();

        } catch (IOException e) {
            e.printStackTrace();

            return false;
        }

        long size = new File(mFilePath).length();

        ContentValues values = new ContentValues(8);

        // store the details
        values.put(MediaStore.Images.Media.TITLE, fileName);
        values.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
        values.put(MediaStore.Images.Media.DATE_ADDED, currentTime);
        values.put(MediaStore.Images.Media.MIME_TYPE, mimeType);
        values.put(MediaStore.Images.Media.DESCRIPTION, fileDescription);
        values.put(MediaStore.Images.Media.ORIENTATION, 0);
        values.put(MediaStore.Images.Media.DATA, mFilePath);
        values.put(MediaStore.Images.Media.SIZE, size);

        return getContext().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values) != null;
    }

    public Bitmap getChartBitmap() {
        // 创建一个bitmap 根据我们自定义view的大小
        Bitmap returnedBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.RGB_565);
        // 绑定canvas
        Canvas canvas = new Canvas(returnedBitmap);
        // 获取视图的背景
        Drawable bgDrawable = getBackground();
//        canvas.drawColor(Color.TRANSPARENT);
        if (bgDrawable != null)
            // 如果有就绘制
            bgDrawable.draw(canvas);
        else
            // 没有就绘制白色
            canvas.drawColor(Color.WHITE);
        // 绘制
        draw(canvas);
        return returnedBitmap;
    }

    public String getPath() {
        return mFilePath;
    }

    public interface PaletteListener {
        void onStartDraw();

        void onDrawing();

        void onFinishDraw(ArrayList<Point> points, boolean isClose);
    }
}
